<?php


namespace app\admin\library\builder\ext;


use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class Twig extends AbstractExtension
{
    private $config;

    public function __construct($config)
    {
        $this->config = $config;
    }

    // 资源加载器
    public function _load($type, $path, $autoVersion = false)
    {
        if ($autoVersion) {
            $path .= '?v=' . $_SERVER['REQUEST_TIME'];
        }
        if ($type === 'css') {
            echo '<link rel="stylesheet" href="/static/admin/' . $path . '"/>';
        } elseif ($type === 'js') {
            echo '<script src="/static/admin/' . $path . '"></script>';
        } else {
            return '/static/admin/' . $path;
        }
    }

    // 生成URL
    public function _url($uri)
    {
        return url($uri);
    }

    // json
    public function _json($data)
    {
        return json_encode($data);
    }

    // icon格式化
    public function _icon($icon)
    {
        // layui-icon layui-icon-
        if (strpos($icon, ':') === false) {
            return 'layui-icon layui-icon-' . $icon;
        }
        list($pre, $icon) = explode(':', $icon);
        if (isset($this->config['icon'])) {
            $pre = $this->config['icon'][$pre];
        }
        return $pre . $icon;
    }

    // 简化变量输出值
    public function _varformat($row, $key)
    {
        if (strpos($key, '.') === false) {
            return $row[$key];
        }
        $tmp = explode('.', $key);
        $data = $row;
        foreach ($tmp as $v) {
            if (!isset($data[$v])) {
                return '';
            }
            $data = $data[$v];
        }
        return $data;
    }

    // 加载css
    public function _loadconfcss()
    {
        return implode("\r\n", array_map(function ($path) {
            return $this->_load('css', $path);
        }, $this->config['css'] ?? []));
    }

    public function getFunctions()
    {
        $methods = array_map(function ($str) {
            return substr($str, 1);
        }, array_filter(get_class_methods($this), function ($str) {
            return substr($str, 0, 1) === '_';
        }));

        $funcs = [];
        foreach ($methods as $method) {
            $funcs[] = new TwigFunction($method, [$this, '_' . $method]);
        }
        unset($methods);

        return $funcs;
    }

}